import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score

# 1. 创建模拟数据
data = {
    "Size": [1400, 1600, 1700, 1875, 1100, 1550, 2350, 2450, 1425, 1700],
    "Bedrooms": [3, 3, 3, 4, 2, 3, 4, 4, 2, 3],
    "Price": [245000, 312000, 279000, 308000, 199000, 219000, 405000, 324000, 220000, 240000]
}
df = pd.DataFrame(data)

# 2. 数据预处理
X = df[['Size', 'Bedrooms']]  # 选择特征
y = df['Price']  # 目标变量

# 3. 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 4. 训练模型
model = LinearRegression()
model.fit(X_train, y_train)

# 5. 预测
y_pred = model.predict(X_test)

# 6. 评估模型
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)

print(f"均方误差（MSE）: {mse}")
print(f"决定系数（R²）: {r2}")

# 7. 可视化结果（仅适用于单变量情况）
plt.scatter(X_test['Size'], y_test, color='blue', label='真实值')
plt.scatter(X_test['Size'], y_pred, color='red', label='预测值')
plt.xlabel('Size')
plt.ylabel('Price')
plt.legend()
plt.show()
